/*
 * 智能测肤的折线图组件
 * @Author:ljb
 * @Date: 2018-05-09 15:17:36
 * @Last Modified by: ljb
 * @Last Modified time: 2018-10-29 13:51:23
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>

    .line-chart {
        width : 100%;
        height : 231px;
        margin-top : 20px;
    }

</style>
<template>

	<div
		id="touch_line_chart"
		ref="touch_line_chart"
		class="line-chart" />

</template>

<script>

import echarts from 'echarts';

export default {
	name: 'LineChartComponent',
	props: {

		chartData: {
			type: Array,
			default() {
				return [];
			},
		},

	},
	data() {
		return {

			max_value_map: {
				water: 100,
				oil: 50,
				flex: 10,
			},

			color_map: {

				water: 'rgb(33,152,253)',

				oil: 'rgb(254,173,47)',

				flex: 'rgb(255,115,141)',

			},

			line_chart: null,

			current_time: '',		// 当前选中的x坐标

			x: 0, // 图表的tooltip的x轴坐标

			y: 0, // 图表的tooltip的x轴坐标

		};
	},
	watch: {

		chartData() {
			this.initChartData();
		},

	},
	mounted() {
		this.line_chart = echarts.init(this.$refs.touch_line_chart);

		this.initChartData();
	},
	beforeDestroy() {
		this.line_chart.dispose();
	},
	methods: {

		/**
         * 初始化折线图data
         * @return {undefined}
         */
		initChartData() {
			if (this.chartData.length === 0) return;

			const need_data = ['water', 'oil', 'flex'];

			this.formatData(need_data);
		},

		/**
         * 设置echarts
         * @param  {Array} xAxis  {x轴}
         * @param  {Array} series {数据}
         * @return {undefined}
         */
		setEchartOption({
			legend_data, grid, xAxis, yAxis, series, dataZoom,
		}) {
			const self = this;

			this.line_chart.clear();

			const option = {
				tooltip: {
					trigger: 'axis',
					alwaysShowContent: true,
					triggerOn: 'click',
					axisPointer: {
						axis: 'x',
						label: {
							show: true,
							formatter(params) {
								const date = params.value.split(' ').shift().split('-');

								return (`${date[1]}-${date[2]}`);
							},
						},
					},
					position(point, param) {
						if (self.x !== point[0] || self.y !== point[1]) {
							[self.x, self.y] = point;
							self.current_time = param[0].name;
							self.$emit('show', param[0].name);
						}
					},
				},
				legend: {
					orient: 'vertical',
					data: legend_data,
					x: 'left',
				},
				axisPointer: {
					snap: true,
					lineStyle: {
						color: '#ccc',
					},
					link: {
						xAxisIndex: 'all',
					},
				},
				dataZoom: [
					{ // 这个dataZoom组件，也控制x轴。
						type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
						realtime: true,
						start: 100 - dataZoom,
						end: 100,
						zoomLock: true,
						xAxisIndex: [0, 1, 2],
					},
				],
				grid,
				xAxis,
				yAxis,
				series,
			};

			this.line_chart.setOption(option);

			this.$emit('show', this.chartData[this.chartData.length - 1].created_at);
		},

		/**
         * 格式化数据成echart配置项所需数据
         * @param  {Array} need_data {需要展示的数据}
         * @return {undefined}
         */
		formatData(need_data) {
			const chart_option = {

				legend_data: [],

				grid: [],

				xAxis: [],

				yAxis: [],

				series: [],

				dataZoom: 5,

			};

			const self = this;

			const device_width = document.querySelector('.line-chart').offsetWidth;

			const data_length = this.chartData.length;

			chart_option.dataZoom = (parseFloat((device_width / 70).toFixed(2)) * 100) / data_length;// 根据屏幕宽度计算显示的条目数

			need_data.forEach((data, index) => {
				const grid_option = {
					left: 0,
					right: 75,
					top: 70,
					height: '60%',
				};

				chart_option.grid.push(grid_option);

				self.assembleData(chart_option, data, index);
			});

			this.setEchartOption(chart_option);
		},

		/**
         * 组装数据
         * @param  {Object} option      {echart配置项对象}
         * @param  {string} data_type       {当前需要取测肤数据类型的类型，water，oil，flex}
         * @param  {number} array_index {测肤数据类型在数组的index}
         * @return {undefined}
         */
		assembleData(option, data_type, array_index) {
			const self = this;

			let series_name = '';

			const xAxis_data = [];

			const series_data = [];

			switch (data_type) {
			case 'water':

				series_name = `${this.$t('report.water')}（%）`; // 水分

				self.chartData.forEach(({ water, created_at }) => {
					series_data.push(`${Number(water)}`);

					xAxis_data.push(`${created_at}`);
				});

				break;

			case 'oil':

				series_name = `${this.$t('report.oil')}（%）`; // 油分

				self.chartData.forEach(({ oil, created_at }) => {
					series_data.push(`${Number(oil)}`);

					xAxis_data.push(`${created_at}`);
				});

				break;

			default:

				series_name = `${this.$t('report.elastic')}`; // '弹性';

				self.chartData.forEach(({ flex, created_at }) => {
					series_data.push(`${Number(flex)}`);

					xAxis_data.push(`${created_at}`);
				});

				break;
			}

			// 配置显示的数据
			const series = {
				xAxisIndex: array_index,
				yAxisIndex: array_index,
				name: series_name,
				type: 'line',
				symbol: 'circle',
				symbolSize: 8,
				hoverAnimation: false,
				silent: true,
				itemStyle: {
					color: self.color_map[data_type],
				},
				lineStyle: {
					color: self.color_map[data_type],
				},
				data: series_data,
			};

			// 配置x轴数据
			const xAxis = {
				show: array_index === 0,
				gridIndex: array_index,
				type: 'category',
				axisLine: {
					onZero: true,
					lineStyle: {
						color: '#c179f8',
					},
				},
				data: xAxis_data,
				axisTick: {
					interval: 0,
				},
				axisLabel: {
					interval: 0,
					color: '#333',
					formatter(value) {
						const date = value.split(' ').shift().split('-');

						return (`${date[1]}-${date[2]}`);
					},
				},
			};

			// 配置y轴数据
			const yAxis = {
				gridIndex: array_index,
				show: false,
				name: series_name,
				type: 'value',
				max: this.max_value_map[data_type],
				splitLine: {
					show: false,
				},
			};

			option.legend_data.push(series_name);
			option.xAxis.push(xAxis);
			option.yAxis.push(yAxis);
			option.series.push(series);
		},

	},
};
</script>
